package action.user;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetailsService;

import service.UserService;

import com.opensymphony.xwork2.ActionSupport;

public class ModifyPasswordAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    private String oldPassword;

    private String newPassword;

    private String newPasswordConfirm;

    private String status;

    private String failType;

    private UserDetailsService jdbcUserDetailsService;
    
    private UserService userService;
    
    private String userName;

    public String modifyPassword() {

        status = "failure";

        SecurityContext ctx = SecurityContextHolder.getContext();
        String name = ctx.getAuthentication().getName();

        if (!jdbcUserDetailsService.loadUserByUsername(name).getPassword().equals(oldPassword)) {
            failType = "OLDPASSWRONG";

        } else if (!newPasswordConfirm.equals(newPassword)) {
            failType = "NEWPASSCONWRONG";

        } else {
            status = userService.changePassword(name, newPassword);
        }
        return SUCCESS;
    }

    public String clearPassword() {
        status = userService.changePassword(userName, DigestUtils.shaHex("000000"));
        return SUCCESS;
    }
    public String getStatus() {
        return status;
    }

    public String getFailType() {
        return failType;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public void setNewPasswordConfirm(String newPasswordConfirm) {
        this.newPasswordConfirm = newPasswordConfirm;
    }

    public void setJdbcUserDetailsService(UserDetailsService jdbcUserDetailsService) {
        this.jdbcUserDetailsService = jdbcUserDetailsService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}
